<!--
 * @Description: 
 * @Author: xuzp4
-->
<template>
  <el-dialog
    class="toast-dialog"
    :visible.sync="_visible"
    :close-on-click-modal="false"
    :title="!isEdit ? $t('sys_equ_addEqu') : $t('sys_equ_title_edit')"
    :append-to-body="true"
    width="520px"
    :before-close="handleClose"
  >
    <div class="content d-flex jc-center ai-center">
      <el-form ref="form" :model="formData" :rules="rules" label-width="140px">
        <el-form-item v-if="isEdit" :label="$t('sys_equ_chan')">
          <el-input disabled v-model="formData.channel" />
        </el-form-item>
        <!-- 设备类型 -->
        <el-form-item :label="$t('sys_equ_equType')" prop="camera_mode">
          <el-select
            :disabled="isEdit"
            v-model="formData.camera_mode"
            :placeholder="$t('choose')"
            @change="changeCameraMode"
          >
            <el-option
              v-for="item in equip_type_list"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 通道名称 -->
        <el-form-item :label="$t('sys_equ_chanName')" prop="camera_name">
          <el-input v-model="formData.camera_name" />
        </el-form-item>
        <!-- 厂商 -->
        <el-form-item
          v-if="is_IMAGE"
          :label="$t('manufacturer')"
          prop="manufacturer"
        >
          <el-select v-model="formData.vendor" :placeholder="$t('choose')">
            <el-option
              v-for="item in vendor_list"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 协议 -->
        <el-form-item
          v-if="is_protocol_show"
          :label="$t('sys_equ_protocol')"
          prop="protocol"
        >
          <el-select
            :disabled="isEdit"
            v-model="formData.protocol"
            :placeholder="$t('choose')"
          >
            <el-option
              v-for="item in protocol_list"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 取帧间隔(s) -->
        <el-form-item
          v-if="is_VIDEO"
          :label="$t('sys_equ_frame_interval')"
          prop="frame_interval"
        >
          <el-input-number v-model="formData.frame_interval" :min="3" :max="25"/>
        </el-form-item>
        <!-- 抓拍策略 -->
        <el-form-item
          v-if="is_VIDEO"
          :label="$t('sys_equ_strategy')"
          prop="snap_mode"
        >
          <el-select v-model="formData.snap_mode" :placeholder="$t('choose')">
            <el-option
              v-for="item in snap_mode_list"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 任务类型 -->
        <el-form-item :label="$t('task_type')" prop="task_type">
          <el-select
            v-model="formData.task_type"
            multiple
            :placeholder="$t('choose')"
          >
            <el-option
              v-for="item in task_type_list"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="is_task_type_disabled(item.value)"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 人像库 -->
        <el-form-item
          v-if="is_lib_ids_show"
          :label="$t('sys_equ_libTag')"
          prop="lib_ids"
        >
          <LibSelect v-model="formData.lib_ids" multiple />
        </el-form-item>
        <!-- 车辆库 -->
        <el-form-item
          v-if="is_vehicle_lib_ids_show"
          :label="$t('vehiclelibraryNameTip')"
          prop="vehicle_lib_ids"
        >
          <el-select
            v-model="formData.vehicle_lib_ids"
            multiple
            :placeholder="$t('choose')"
          >
            <el-option
              v-for="item in vehicleLibList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 重复告警最小间隔(s) -->
        <el-form-item
          v-if="is_dup_alarm_gap_show"
          :label="$t('indoor.warn_time')"
          prop="dup_alarm_gap"
        >
          <el-input-number v-model="formData.dup_alarm_gap" :min="1" />
        </el-form-item>
        <!-- 活体检测开关 -->
        <el-form-item
          v-if="is_liveness_switch_show"
          :label="$t('sys_equ_liveness_switch')"
          prop="liveness_switch"
        >
          <el-switch
            v-model="formData.liveness_switch"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <!-- 活体检测阈值(%) -->
        <el-form-item
          v-if="is_liveness_threshold_show"
          :label="$t('sys_equ_liveness_threshold')"
          prop="liveness_threshold"
        >
          <el-input-number v-model="formData.liveness_threshold" :min="1" />
        </el-form-item>
        <!-- ip地址 -->
        <el-form-item v-if="is_ip_show" :label="$t('sys_equ_ipAddr')" prop="ip">
          <NetworkInput v-model="formData.ip" />
        </el-form-item>
        <!-- 端口 -->
        <el-form-item
          v-if="is_port_show"
          :label="$t('sys_equ_port')"
          prop="port"
        >
          <el-input v-model="formData.port" @input="handleInputPort" />
        </el-form-item>

        <!-- url -->
        <el-form-item
          v-if="is_url_show"
          :label="$t('inputViperUrl')"
          prop="url"
        >
          <el-input v-model="formData.url" />
        </el-form-item>
        <!-- 用户名 -->
        <el-form-item
          v-if="is_camera_user_show"
          :label="$t('sys_equ_userName')"
          prop="camera_user"
        >
          <el-input v-model.trim="formData.camera_user" />
        </el-form-item>
        <!-- 密码 -->
        <el-form-item
          v-if="is_camera_pwd_show"
          :label="$t('sys_equ_password')"
          prop="camera_pwd"
        >
          <PasswordInput v-model="formData.camera_pwd" />
        </el-form-item>
        <!-- 平台地址 -->
        <el-form-item
          v-if="is_trd_login_url_show"
          :label="$t('sys_equ_trd_login_url')"
          prop="trd_login_url"
        >
          <el-input v-model.trim="formData.trd_login_url" />
        </el-form-item>
        <!-- 取流地址 -->
        <el-form-item
          v-if="is_trd_fetch_stream_url_show"
          :label="$t('sys_equ_trd_stream_url')"
          prop="trd_fetch_stream_url"
        >
          <el-input v-model.trim="formData.trd_fetch_stream_url" />
        </el-form-item>
        <!-- SIP服务器IP -->
        <el-form-item
          v-if="is_sipip_show"
          :label="$t('sys_equ_ip_address_spi')"
          prop="ip"
        >
          <NetworkInput v-model="formData.ip" />
        </el-form-item>
        <!-- SIP服务器端口 -->
        <el-form-item
          v-if="is_sipport_show"
          :label="$t('sys_equ_port_spi')"
          prop="port"
        >
          <el-input v-model="formData.port" @input="handleInputPort" />
        </el-form-item>
        <!-- SIP服务器ID -->
        <el-form-item
          v-if="is_server_sip_id_show"
          :label="$t('sys_equ_serverID')"
          prop="server_sip_id"
        >
          <el-input v-model="formData.server_sip_id" />
        </el-form-item>
        <!-- SIP相机ID -->
        <el-form-item
          v-if="is_camera_sip_id_show"
          :label="$t('sys_equ_cameraID')"
          prop="camera_sip_id"
        >
          <el-input v-model="formData.camera_sip_id" />
        </el-form-item>
        <!-- 鉴权 -->
        <el-form-item v-if="is_auth_show" :label="$t('auth')" prop="">
          <el-switch v-model="auth" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <!-- gb28181 密码 -->
        <el-form-item
          v-if="is_auth_camera_pwd_show"
          :label="$t('sys_equ_password')"
          prop="camera_pwd"
        >
          <PasswordInput v-model="formData.camera_pwd" />
        </el-form-item>
        <!-- 阈值% -->
        <el-form-item
          v-if="is_threshold_show"
          :label="$t('sys_equ_threshold')"
          prop="threshold"
        >
          <el-input-number v-model="formData.threshold" />
        </el-form-item>
        <el-form-item
          v-if="isEdit && is_VIDEO"
          :label="$t('minimum_face_pix_setting')"
          prop="facesize_min"
        >
          <el-input class="pix-input" v-model="formData.facesize_min" />
          <i class="el-icon-close"></i>
          <el-input class="pix-input" v-model="formData.facesize_min" />
        </el-form-item>
        <el-form-item
          v-if="isEdit && is_VIDEO"
          :label="$t('maximum_face_pix_setting')"
          prop="facesize_max"
        >
          <el-input class="pix-input" v-model="formData.facesize_max" />
          <i class="el-icon-close"></i>
          <el-input class="pix-input" v-model="formData.facesize_max" />
        </el-form-item>
        <el-form-item
          v-if="isEdit && is_VIDEO"
          :label="$t('minimum_body_pix_setting')"
          prop="bodysize_min"
        >
          <el-input class="pix-input" v-model="formData.bodysize_min" />
          <i class="el-icon-close"></i>
          <el-input class="pix-input" v-model="formData.bodysize_min" />
        </el-form-item>
        <el-form-item
          v-if="isEdit && is_VIDEO"
          :label="$t('maximum_body_pix_setting')"
          prop="bodysize_max"
        >
          <el-input class="pix-input" v-model="formData.bodysize_max" />
          <i class="el-icon-close"></i>
          <el-input class="pix-input" v-model="formData.bodysize_max" />
        </el-form-item>
        <RoiVideo
          v-if="isEdit && is_VIDEO && _visible"
          class="roi-wrapper"
          :hasDefault="true"
          :status="formData.status"
          @updateFormData="updateFormData"
          ref="roiVideoRef"
          :formData="formData"
        />
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <MyButton class="cancel" @click="cancel">{{
        $t("common.cancel")
      }}</MyButton>
      <MyButton class="confirm" @click="confirm">{{
        $t("common.confirm")
      }}</MyButton>
    </div>
  </el-dialog>
</template>

<script>
import PasswordInput from "@/components/input/Password.vue";
import { addCamera, editCamera } from "./service";
import util from "@/utils";
import * as CONSTANT from "./CONSTANT";
import RoiVideo from "./RoiVideo";
const IMAGE = "IMAGE";
const VIDEO = "VIDEO";
const FACE = "face";
const defaultForm = {
  camera_mode: VIDEO,
  protocol: "onvif",
  snap_mode: 1,
  frame_interval: 5,
  task_type: [],
  threshold: 85,
  liveness_threshold: 1,
  vendor: "dahua",
  dup_alarm_gap: 5
};
export default {
  components: { PasswordInput, RoiVideo },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: () => {
        return {};
      },
    },
    editType: {
      type: String,
      default: "add",
    },
    vehicleLibList: {
      type: Array,
      default: () => [],
    },
    restPower: {
      type: Number,
      default: 0,
    },
  },
  watch: {
    row: {
      handler(val) {
        if (val) {
          if (this.isEdit) {
            const {
              camera_mode,
              protocol,
              camera_name,
              camera_user,
              camera_pwd,
              snap_mode,
              ip,
              channel,
              position,
              port,
              camera_sip_id,
              facesize_min,
              facesize_max,
              bodysize_min,
              bodysize_max,
              lib_ids,
              vehicle_lib_ids,
              threshold,
              task_type,
              frame_interval,
              liveness_threshold,
              liveness_switch,
              dup_alarm_gap,
              vendor,
              url,
            } = val;
            this.$set(this, "formData", {
              ...defaultForm,
              ...val,
              url,
              camera_mode,
              frame_interval,
              vendor,
              protocol,
              camera_name,
              camera_user,
              camera_pwd,
              snap_mode,
              ip,
              channel,
              position,
              port,
              camera_sip_id,
              facesize_min,
              facesize_max,
              bodysize_min,
              bodysize_max,
              threshold,
              liveness_threshold,
              liveness_switch,
              dup_alarm_gap,
              lib_ids: lib_ids && lib_ids.split(","),
              task_type: task_type && task_type.split(","),
              vehicle_lib_ids: vehicle_lib_ids && vehicle_lib_ids.split(","),
            });
            // 默认绘制区域
            this.$nextTick(() => {
              this.$refs.roiVideoRef.rectData =
                val.camera_roi &&
                val.camera_roi.split(",").map((item) => item / 4);
              this.$refs.roiVideoRef.rect_draw();
            });
          } else {
            this.$set(this, "formData", { ...defaultForm });
          }
        }
      },
      deep: true,
      immediate: true,
    },
    ["formData.camera_mode"](val, oldVal) {
      this.old_camera_mode = oldVal;
    },
  },
  computed: {
    _visible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
    isEdit() {
      return this.editType === "edit";
    },
    // 车辆库
    is_vehicle_lib_ids_show() {
      return (
        this.formData.task_type && this.formData.task_type.includes("vehicle")
      );
    },
    is_IMAGE() {
      return this.formData.camera_mode == IMAGE;
    },
    is_VIDEO() {
      return this.formData.camera_mode == VIDEO;
    },
    // 协议
    is_protocol_show() {
      return this.is_VIDEO;
    },
    // 活体检测阈值
    is_liveness_threshold_show() {
      return (
        this.is_liveness_switch_show && this.formData.liveness_switch === 1
      );
    },
    // 人像库
    is_lib_ids_show() {
      return this.formData.task_type && this.formData.task_type.includes(FACE);
    },
    // 重复告警最小间隔(s)
    is_dup_alarm_gap_show() {
      return (
        this.is_VIDEO &&
        this.is_lib_ids_show &&
        this.formData.lib_ids &&
        this.formData.lib_ids.length > 0
      );
    },
    // 活体检测开关
    is_liveness_switch_show() {
      return (
        this.is_VIDEO &&
        this.formData.task_type &&
        this.formData.task_type.includes(FACE)
      );
    },
    // 阈值%
    is_threshold_show() {
      return (
        this.is_lib_ids_show &&
        this.formData.lib_ids &&
        this.formData.lib_ids.length > 0
      );
    },
    // url
    is_url_show() {
      return this.is_protocol_show && this.formData.protocol === "rtsp";
    },
    is_ip_show() {
      return (
        this.is_IMAGE ||
        (["onvif"].includes(this.formData.protocol) && this.is_VIDEO)
      );
    },
    is_sipip_show() {
      return (
        this.is_IMAGE ||
        (["gb28181"].includes(this.formData.protocol) && this.is_VIDEO)
      );
    },
    is_port_show() {
      return (
        this.is_IMAGE || (this.formData.protocol === "onvif" && this.is_VIDEO)
      );
    },
    is_sipport_show() {
      return (
        this.is_IMAGE || (this.formData.protocol === "gb28181" && this.is_VIDEO)
      );
    },
    is_camera_user_show() {
      return (
        this.is_IMAGE ||
        (["onvif", "vcn"].includes(this.formData.protocol) && this.is_VIDEO)
      );
    },
    is_camera_pwd_show() {
      return this.is_camera_user_show;
    },
    // gb28181 密码
    is_auth_camera_pwd_show() {
      return (
        ["gb28181"].includes(this.formData.protocol) &&
        this.is_VIDEO &&
        this.auth === 1
      );
    },
    is_server_sip_id_show() {
      return this.is_VIDEO && this.formData.protocol === "gb28181";
    },
    is_camera_sip_id_show() {
      return (
        this.is_VIDEO && ["gb28181", "vcn"].includes(this.formData.protocol)
      );
    },
    is_trd_login_url_show() {
      return this.is_VIDEO && this.formData.protocol === "vcn";
    },
    is_trd_fetch_stream_url_show() {
      return this.is_VIDEO && this.formData.protocol === "vcn";
    },
    is_auth_show() {
      return this.is_VIDEO && this.formData.protocol === "gb28181";
    }
  },
  data() {
    const {
      equip_type_list,
      task_type_list,
      protocol_list,
      status_list,
      snap_mode_list,
      vendor_list,
    } = CONSTANT;
    return {
      auth: 0, // gb28181 鉴权
      equip_type_list,
      task_type_list,
      protocol_list,
      status_list,
      snap_mode_list,
      vendor_list,
      formData: {
        ...defaultForm,
      },
      rules: {
        channel: [{ required: true, message: this.$t("channelNameNull") }],
        port: [
          {
            pattern:
              /^(?:[0-9]{1,4}|[1-5][0-9]{4}|6[0-5]{1,2}[0-5]?[0-3]?[0-5]?)$/,
            message: this.$t("inputPort"),
            trigger: "change",
          },
          { required: true, message: this.$t("portNotNull") },
        ],
        dup_alarm_gap: [
          {
            pattern: /^(?:[1-9][0-9]{0,2}|[1-2][0-9]{3}|3[0-5][0-9]{2}|3600)$/,
            message: this.$t("warn_time_tips"),
            trigger: "change",
          },
        ],
        frame_interval: [
          {
            required: true,
            message: this.$t("notNull", {
              name: this.$t("sys_equ_frame_interval"),
            }),
          },
        ],
        task_type: [{ required: true, message: this.$t("task_type_tips") }],
        ip: [{ required: true, message: this.$t("ipAddrNull") }],
        server_sip_id: [
          { required: true, message: this.$t("sys_equ_noserverID") },
        ],
        camera_sip_id: [
          { required: true, message: this.$t("sys_equ_nocameraID") },
        ],
        camera_user: [{ required: true, message: this.$t("inputUserName") }],
        camera_pwd: [{ required: true, message: this.$t("inputUserPwd") }],
        url: [{ required: true, message: this.$t("inputViperUrlErr") }],
        facesize_min: [
          {
            pattern: /^(?:[3-9]\d|[1-9]\d{2}|1000)$/,
            message: this.$t("adv_warn", { min: 30, max: 1000 }),
            trigger: "change",
          },
          {
            required: true,
            message: this.$t("equipment_nonull", {
              name: this.$t("minimum_face_pix_setting"),
            }),
          },
        ],
        facesize_max: [
          {
            pattern: /^(?:[3-9]\d|[1-9]\d{2}|1000)$/,
            message: this.$t("adv_warn", { min: 30, max: 1000 }),
            trigger: "change",
          },
          {
            required: true,
            message: this.$t("equipment_nonull", {
              name: this.$t("minimum_face_pix_setting"),
            }),
          },
        ],
        bodysize_min: [
          {
            pattern: /^(?:[3-9]\d|[1-9]\d{2}|1000)$/,
            message: this.$t("adv_warn", { min: 30, max: 1000 }),
            trigger: "change",
          },
          {
            required: true,
            message: this.$t("equipment_nonull", {
              name: this.$t("minimum_face_pix_setting"),
            }),
          },
        ],
        bodysize_max: [
          {
            pattern: /^(?:[3-9]\d|[1-9]\d{2}|1000)$/,
            message: this.$t("adv_warn", { min: 30, max: 1000 }),
            trigger: "change",
          },
          {
            required: true,
            message: this.$t("equipment_nonull", {
              name: this.$t("minimum_face_pix_setting"),
            }),
          },
        ],
        trd_login_url: [{ required: true, message: this.$t("inputAddr") }],
        trd_fetch_stream_url: [{ required: true, message: this.$t("inputAddr") }],
      },
    };
  },
  methods: {
    changeCameraMode(val) {
      if (val === "VIDEO") {
        if (this.restPower < 2) {
          this.$set(this.formData, "camera_mode", this.old_camera_mode);
          return this.$message.warning(this.$t("unAbleToAddVideoTips"));
        }
      }
    },
    confirm() {
      if (!this.isEdit) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            const params = this.parseFormData(this.formData);
            addCamera(params).then(this.editSuccessCb);
          }
        });
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            const params = this.parseFormData(this.formData);
            editCamera(params).then(this.editSuccessCb);
          }
        });
      }
    },
    updateFormData(data) {
      this.$set(
        this.formData,
        "camera_roi",
        data.rect.map((item) => Math.round(item * 4)).join(",")
      );
    },
    editSuccessCb(res) {
      if (res.code == 0) {
        util.msg.success("edit_success");
        this.$emit("refresh");
        this._visible = false;
      }
    },
    parseFormData(val) {
      return {
        ...val,
        trd_login_user: val.camera_mode === 'vcn' ? val.camera_user : void 0,
        trd_login_pwd: val.camera_mode === 'vcn' ? val.camera_pwd : void 0,
        task_type: val.task_type && val.task_type.join(","),
        lib_ids: val.lib_ids && val.lib_ids.join(","),
        port: Number(val.port),
        vehicle_lib_ids: val.vehicle_lib_ids && val.vehicle_lib_ids.join(","),
        facesize_min: val.facesize_min && Number(val.facesize_min),
        facesize_max: val.facesize_max && Number(val.facesize_max),
        bodysize_min: val.bodysize_min && Number(val.bodysize_min),
        bodysize_max: val.bodysize_max && Number(val.bodysize_max),
      };
    },
    handleInputPort(value) {
      value = value.replace(/\D/g, ""); // 只保留数字
      this.$set(this.formData, "port", value);
    },
    cancel() {
      this.formData = { ...defaultForm };
      this._visible = false;
      this.$refs.roiVideoRef.resetRect() // 清空矩形
    },
    handleClose(done) {
      this.cancel();
      done();
    },
    is_task_type_disabled(val) {
      if (
        this.formData.camera_mode === IMAGE &&
        ["abnormal", "violate_operate"].includes(val)
      ) {
        return true;
      }
    },
  },
};
</script>
<style lang="less" scoped>
.toast-dialog {
  z-index: 9999;
  .content {
    width: 100%;
    /deep/ .el-form {
      width: 100%;
      .video-wrapper {
      }
      .el-input-number--medium {
        width: 300px;
      }
      .el-input {
        width: 300px;
      }
      .sf-ipInput {
        width: 300px;
      }
      .sf-ipInput-item {
        .el-input {
          width: calc(100% - 14px);
        }
      }
      .pix-input {
        width: 135px;
      }
    }
  }
}
</style>
